using MediatR;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Menus.Queries.GetFlatMenus;

public class GetFlatMenusQueryHandler : IRequestHandler<GetFlatMenusQuery, ApiResult<List<MenuFlatDto>>>
{
  private readonly IUnitOfWork _uow;

  public GetFlatMenusQueryHandler(IUnitOfWork uow)
  {
    _uow = uow;
  }

  public async Task<ApiResult<List<MenuFlatDto>>> Handle(GetFlatMenusQuery request, CancellationToken ct)
  {
    var data = await _uow.MenuRepository.GetAllAsync();
    var list = data
        .OrderBy(m => m.ParentId).ThenBy(m => m.Sort)
        .Select(m => new MenuFlatDto
        {
          Id = m.Id,
          Name = m.Name,
          Path = m.Path,
          Icon = m.Icon,
          ParentId = m.ParentId,
          Sort = m.Sort
        })
        .ToList();

    return ApiResult<List<MenuFlatDto>>.Success(list);
  }
}